import express, { Application } from "express";
import { ITodoData } from "../src/js/typings";
import { CORS, readFile, fileOperation } from "./utils";

const app: Application = express();

CORS(app);

app.get("/todolist", function (req, res) {
  const todoList: string = readFile("todo.json");
  res.send(todoList);
});

app.post("/toggle", function (req, res) {
  const id: number = parseInt(req.body.id);
  fileOperation("todo.json", function (todoList: ITodoData[]) {
    return todoList.map((todo: ITodoData) => {
      if (todo.id === id) {
        todo.complete = !todo.complete;
      }
      return todo;
    });
  });
  res.send({
    status: 200,
    msg: "ok",
  });
});

app.post("/remove", function (req, res) {
  const id: number = parseInt(req.body.id);

  fileOperation("todo.json", function (todoList: ITodoData[]) {
    return todoList.filter((todo: ITodoData) => todo.id !== id);
  });
  res.send({
    status: 200,
    msg: "ok",
  });
});

app.post("/add", function (req, res) {
  const todo: ITodoData = JSON.parse(req.body.todo);
  fileOperation("todo.json", function (todoList: ITodoData[]) {
    const isExis = todoList.find((t: ITodoData) => t.content === todo.content);
    if (isExis) {
      res.send({
        msg: "内容已存在",
        code: 100,
      });
      return;
    }
    todoList.push(todo);
    return todoList;
  });
  res.send({
    msg: "ok",
    code: 200,
  });
});

app.listen(8080, () => {
  console.log("Listening on port http://localhost:8080/");
});
